package com.caiyi.financial.nirvana.sms.gateway.sgip.handler;

import com.caiyi.financial.nirvana.sms.gateway.DefaultGateWay;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.CMPPMessageTool;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.GatewayControlHandler;
import com.caiyi.financial.nirvana.sms.gateway.sgip.SGIPHeader;
import com.caiyi.financial.nirvana.sms.gateway.sgip.message.SGIPMessage;
import com.caiyi.financial.nirvana.sms.gateway.sgip.message.body.SGIPBind;
import com.caiyi.financial.nirvana.sms.util.Constant;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SGIPControlHandler extends GatewayControlHandler {

    private static Logger logger = LoggerFactory.getLogger(SGIPControlHandler.class);

    public SGIPControlHandler(DefaultGateWay gateWayInfo) {
        this.gateWayInfo = gateWayInfo;
    }

    @Override
    public void doLogin(ChannelHandlerContext ctx) {
        SGIPMessage loginMessage = new SGIPMessage();
        SGIPHeader header = new SGIPHeader();
        header.setCommandID(SGIPMessage.SGIP_BIND);
        //header.setSpNodeNum((int)Long.parseLong(gateWayInfo.getSpNodeNumber()));
        header.setTimestamp(CMPPMessageTool.getMMDDHHMMSS());
        header.setSequenceId(Constant.seqNo.incrementAndGet());
        loginMessage.setHeader(header);
        logger.info("{} 正在登陆, account : {}, password : {}", gateWayInfo.info.getName(), gateWayInfo.info.getAccount(), gateWayInfo.info.getPassword());
        SGIPBind body = new SGIPBind(gateWayInfo.info.getAccount(), gateWayInfo.info.getPassword());
        loginMessage.setBody(body);
        ctx.writeAndFlush(loginMessage);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        logger.info("sgip userEventTriggered !!!");
//        if (evt instanceof IdleStateEvent) {
//            IdleStateEvent event = (IdleStateEvent) evt;
//            //读空闲事件，触发重连，关闭当前连接；否则发送心跳包给服务器
//            if (event.state().equals(IdleState.READER_IDLE)) {
//                logger.info(gateWayInfo.info.getName() + " 触发读空闲事件，连接关闭！");
//                ctx.close();
//            }
//        }
    }
}
